package com.pi.base.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.pi.community.common.CommunityConst;
import com.pi.base.constant.SysStatics;
import com.pi.community.dto.CommunityDto;
import com.pi.base.encrypt.MD5Encrypt;
import com.pi.base.entity.*;
import com.pi.base.mapper.SysRoleMapper;
import com.pi.base.util.Pinyin4jUtil;
import org.apache.http.util.Asserts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pi.base.common.BasePage;
import com.pi.base.common.BaseResult;
import com.pi.base.mapper.BaseSysUserMapper;
import com.pi.base.mapper.SysGroupMapper;
import com.pi.base.mapper.SysUserMapper;
import com.pi.base.service.BaseService;
import com.pi.base.service.ISysGroupService;
import com.pi.base.util.MapBuilder;
import com.pi.base.util.PropKit;
import com.pi.base.util.ValidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service("sysGroupService")
public class SysGroupService  extends BaseService<SysGroup>  implements ISysGroupService{

	private final Logger logger = LoggerFactory.getLogger(SysGroupService.class);

	@Autowired
	private SysGroupMapper sysGroupMapper;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private BaseSysUserMapper baseSysUserMapper ;
	@Autowired
	private SysRoleMapper sysRoleMapper;
	
	@Override
	public SysGroup getGroupById(int groupId) throws Exception {
		return sysGroupMapper.selectByPrimaryKey(groupId);
	}

	@Override
	public BasePage<SysUser> listUserByGroupId(int groupId,int page,int rows) throws Exception {
		SysUser searchUser = new SysUser();
		searchUser.setGroupid(groupId);
		Page<SysUser> pageInfo = PageHelper.startPage(page, rows); 
		List<SysUser> userList = sysUserMapper.select(searchUser);
		return new BasePage<SysUser>(pageInfo.getTotal(),userList);
	}

	@Override
	public void insertSysGroup(SysGroup newGroup) throws Exception {
		sysGroupMapper.insertSelective(newGroup);
	}

	@Override
	public int countGroupCode(Integer groupId, String groupCode)
			throws Exception {
		SysGroupExample searchGroupExample = new SysGroupExample();
		SysGroupExample.Criteria criteria = searchGroupExample.createCriteria();
		if(groupId != null){
			criteria.andIdNotEqualTo(groupId);
		}
		criteria.andCodeEqualTo(groupCode);
		return sysGroupMapper.selectCountByExample(searchGroupExample);
	}

	@Override
	public BaseResult updateSysGroup(SysGroup updateGroup) throws Exception {
		SysGroup oldGroup = sysGroupMapper.selectByPrimaryKey(updateGroup.getId());
		if(oldGroup == null){
			return BaseResult.newErrorResult("该分组不存在，修改失败");
		}
		String oldGroupName = oldGroup.getName();
		sysGroupMapper.updateByPrimaryKeySelective(updateGroup);
		if(!ValidUtil.isBlank(updateGroup.getName()) && !updateGroup.getName().equals(oldGroupName)){ //修改用户分组名称
			SysUserExample userExample = new SysUserExample();
			userExample.createCriteria().andGroupidEqualTo(updateGroup.getId());
			SysUser updateUser = new SysUser();
			updateUser.setGroupname(updateGroup.getName());
			sysUserMapper.updateByExampleSelective(updateUser, userExample);
		}
		return BaseResult.newSuccessResult("修改成功");
	}

	@Override
	public SysGroup getCompanyByGroup(SysGroup selectGroup) throws Exception {
		if (selectGroup.getType() == 0 || selectGroup.getType() == 1) {
			return selectGroup;
		}
		PropKit.use("tableMap.properties");
		Map<String,Object> params = new MapBuilder.Builder<Object>().
				map("groupId",selectGroup.getId()).
				map("groupType","1").
				map("tableSyGroup",PropKit.get("sys_group","sys_group")).
				map("function1",PropKit.get("queryGroupWithParentByID","queryGroupWithParentByID")).build().map();
		return getSingelFromList(baseSysUserMapper.queryGroupWithParentByID(params));
	}

	@Override
	public BaseResult deleteGroup(int groupId) throws Exception {
		SysUser searchUser = new SysUser();
		searchUser.setGroupid(groupId);
		if(sysUserMapper.selectCount(searchUser) > 0){
			return BaseResult.newErrorResult("该分组下面有用户，不能删除。");
		}
		sysGroupMapper.deleteByPrimaryKey(groupId);
		return BaseResult.newSuccessResult("删除成功");
	}

	@Override
	public BaseResult addReCompanyWithGroup(CommunityDto communityDto)  {
		Asserts.notNull(communityDto,"物业公司");
		Asserts.notNull(communityDto.getCommunityId(),"物业公司ID");
		Asserts.notBlank(communityDto.getCommunityName(),"物业公司名称");
        //0.查找固定物业管理员角色
		SysRoleExample roleExample = new SysRoleExample();
		roleExample.createCriteria().andNameEqualTo(CommunityConst.ROLE_COMMUNITY_NAME);
		SysRole sysRole = getSingelFromList(sysRoleMapper.selectByExample(roleExample));
		if(sysRole == null){
			return BaseResult.newErrorResult("生成失败，请先创建物业公司管理员这个角色");
		}
		// check物业是否存在
		if(queryCtByCommunityId(communityDto.getCommunityId()) > 0){
			return BaseResult.newErrorResult("物业公司已经存在");
		}
		// 1.新增物业公司的分组
		SysGroup newGroup = generateGeGroup(communityDto);
		Integer groupId = sysGroupMapper.insertSelective(newGroup);

		// 2.添加该物业公司的管理人员
		String communityUserName = generateSysAdminName(newGroup.getName(),communityDto.getCommunityId()+"");
		SysUser reAdmin = generateGeSysuser(newGroup, 1, sysRole,communityUserName);
		sysUserMapper.insertSelective(reAdmin);
        //4.将管理员的名称显示到反馈结果中
		return BaseResult.newSuccessResult("新增物业管理员成功",communityUserName);
	}

	private int queryCtByCommunityId(Long communityId){
		String code = CommunityConst.COMMUNITY_PRE+communityId;
		SysGroupExample example = new SysGroupExample();
		example.createCriteria().andCodeEqualTo(code);
		return sysGroupMapper.selectCountByExample(example);
	}

	/**
	 * 生成该物业公司的分组信息
	 * @param reCompany
	 * @return
	 */
	private static SysGroup generateGeGroup(CommunityDto reCompany){
		SysGroup newGroup = new SysGroup();
		newGroup.setName(reCompany.getCommunityName());
		newGroup.setCode(CommunityConst.COMMUNITY_PRE+reCompany.getCommunityId());
		//newGroup.setDescr(reCompany.getRecName());
		newGroup.setAddress(reCompany.getCommunityAddress());

		newGroup.setFullname(reCompany.getCommunityName());
		newGroup.setTelephone(reCompany.getContact());

		newGroup.setState(0);  //状态为可用
		newGroup.setCreatetime(new Date());
		newGroup.setCreatername(CommunityConst.HOMELOCK_NAME); //添加的系平台
		newGroup.setParentid(CommunityConst.RECOMPANY_GROUP_PID); //分组父Id：默认1
		newGroup.setLevel(CommunityConst.RECOMPANY_GROUP_LEVEL); //分组等级：默认2
		newGroup.setType(CommunityConst.RECOMPANY_GROUP_TYPE); //分组类型：默认1
		return newGroup;
	}


	/**
	 * 生成物业公司后台管理人员账号
	 * @param newGroup
	 * @param index
	 * @param reRole
	 * @param reUserName
	 * @return
	 */
	private static SysUser generateGeSysuser(SysGroup newGroup,int index,SysRole reRole,String reUserName){
		SysUser user = new SysUser();
		user.setName(newGroup.getName()+CommunityConst.RECOMPANY_ADMIN_SUFFIX); //姓名
		user.setUsername(reUserName);  //拼音首字母+序号
		user.setNickname(user.getName());
		user.setCode(newGroup.getCode()+index);  //物业公司编号+序号
		user.setPassword(MD5Encrypt.md5(user.getUsername()));
		user.setSuperadmin(SysStatics.SysUser_NotSuperAdmin);  //不是超级管理员0
		user.setUserstate(SysStatics.SysUserState_Normal); //状态正常
		user.setAddress(newGroup.getAddress()); //地址
		user.setCreatername(newGroup.getCreatername()); //创建人
		user.setCreatetime(new Date()); //创建时间
		user.setTelephone(newGroup.getTelephone());//联系电话
		user.setRoleid(reRole.getId()); //物业公司管理员
		user.setRolename(reRole.getName());
		user.setGroupid(newGroup.getId());
		user.setGroupname(newGroup.getName());
		user.setAreaid(newGroup.getId());  //二级部门
		user.setAreaname(newGroup.getName());
		user.setAreaeasyname(newGroup.getCode());
		user.setItem1(newGroup.getCode()); //物业公司的code,该字段不为空则说明来管理员是关联物业公司的管理员
		return user;
	}

	/**
	 * 物业管理员名称规则
	 *  物业公司名称 拼音+公司code
	 * @param groupName
	 * @param gsGroupCode
	 * @return
	 * @throws SQLException
	 */
	private String generateSysAdminName(String groupName,String gsGroupCode)  {
		groupName = groupName.replaceAll("区", "q");//防止翻译成区的多音字首字母o
		String reNamePre = Pinyin4jUtil.converterToFirstSpellSingle(groupName)+gsGroupCode;
		return reNamePre;
	}


}
